package com.ideaction.game.sec;

import java.io.UnsupportedEncodingException;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import com.ideaction.game.utils.SecStringUtil;


/**
 * 在发送body之前进行拦截 body内容加密
 * 
 * @author ZGame
 *
 *
 */
@ControllerAdvice
public class SecResponseBodyAdvice implements ResponseBodyAdvice<Object> {

	@Value("${security.open}")
	private boolean openSecurity;

	/**
	 * 是否开启response拦截功能
	 */
	@Override
	public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
		return openSecurity;
	}

	/**
	 * response加密
	 */
	@Override
	public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
			Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
			ServerHttpResponse response) {
		try {
			if(body instanceof String){
				String bodyStr = (String)body;
				return SecStringUtil.secString(bodyStr);
			}else{
				return body;
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}
}
